// 导入createStore方法，用来创建仓库
import { createStore } from "redux";

// 初始化state
const initState = {
  age: 18
}

// 统一处理action的类型，整个项目都保持一致
const types = {
  OLD: 'OLD',
  YOUNG: 'YOUNG',
  CHANGE: 'CHANGE',
}

// 统一处理action——action creator
export const actions = {
  // action是一个对象，里面有很多方法，调用后会返回action对象
  old: () => ({ type: types.OLD }),
  young: () => ({ type: types.YOUNG }),
  change: (age) => ({ type: types.CHANGE, age: age })
}
// 通过reducer这个纯函数修改state
const reducer = (state = initState, action) => {
  switch (action.type) {
    case types.OLD:
      return {
        ...state,
        age: state.age + 1
      }
    case types.YOUNG:
      return {
        ...state,
        age: state.age - 1
      }
    case types.CHANGE:
      return {
        ...state,
        age: action.age
      }
    default:
      return state
  }
}

// 创建仓库
const store = createStore(reducer);

export default store;